package cscie160.project.atm;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
/**
 * This class is the actual ATMFactory.
 * Create the RMI ready implementation of the factory interface.
 * Designed to return a remote reference to an ATM instance. 
 * @author Michael Melnikov 
*/
public class ATMFactoryImpl extends UnicastRemoteObject implements ATMFactory
{
	/**
	* main method manages the ATMFactoryImpl launching
	* @param args String[]
	*/
	public static void main(String args[])
	{
        //Create and install a security manager
        System.setSecurityManager(new java.rmi.RMISecurityManager());
        try
		{
            int atmPort = 1099;
            int bankServerPort = 50001;
            if (args.length > 0 && !(args[0].equals("?") || args[0].equalsIgnoreCase("help")))
			{
                try
				{
                    atmPort = Integer.parseInt(args[0]);
                } catch (NumberFormatException nfex){
                    System.out.println("Provided argument\"" + args[0] + "\" can't be a port");
                    return;
                }
            }
            java.rmi.registry.Registry registry =
                 java.rmi.registry.LocateRegistry.createRegistry(atmPort);
            ATMFactoryImpl anAtmFact = new ATMFactoryImpl();
            String atmFactoryRebindUrl = "//localhost:" + Integer.toString(atmPort) + "/atmfactory";
            Naming.rebind(atmFactoryRebindUrl, anAtmFact);
            System.out.println(anAtmFact.getClass().getName() + " is bound in registry on port " + Integer.toString(atmPort));    
        } catch (Exception e)
		{
            System.out.println("Server err: " + e.getClass().getName() + ". Message="+e.getMessage());
            e.printStackTrace();
        }
        System.out.println(ATMFactoryImpl.class.getName() + " is exiting its \"main()\" method");
    }

    /**
    * no-args constructor. makes ATMFactory instance.
    */
    public ATMFactoryImpl() throws RemoteException
    {
        super();
    }
    
    /**
    * makes ATM instance.
    * @param bankServerPort int
    * @return atm ATM.
    */    
    public ATM getATM(int bankServerPort) throws RemoteException
    {
        ATM atm = new ATMImpl(bankServerPort);
        return atm;
    }
}